import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:shop/models/pcontentModel.dart';
import 'package:shop/tools/cartServices.dart';
import 'package:shop/tools/httpsClient.dart';
import 'package:shop/tools/screenAdapter.dart';

class ProductContentController extends GetxController {
  ScrollController scrollController = ScrollController();
  HttpsClient httpsClient = HttpsClient();

  // 商品内容详情数据
  var pcontent = PContentItemModel().obs;

  // 将attr数据重构
  RxList<PContentAttrModel> pcontentAttr = <PContentAttrModel>[].obs;

  // 透明度
  RxDouble opacity = 0.0.obs;

  // 是否显示Tabs

  RxBool showTabs = false.obs;

  // 顶部Tab中间文字
  List tabList = [
    {"id": 1, "title": "商品"},
    {"id": 2, "title": "详情"},
    {"id": 3, "title": "推荐"},
  ];
  RxInt selectIndex = 1.obs;

  // 定义GlobalKey
  GlobalKey gb1 = GlobalKey();
  GlobalKey gb2 = GlobalKey();
  GlobalKey gb3 = GlobalKey();

  // tabs的位置
  double gk2Position = 0;
  double gk3Position = 0;

  // 是否展示subTitle
  RxBool showSubHeaderTabs = false.obs;

  // 修改getContainerPosition方法
  bool _hasCalculatedPositions = false;

  // 保存筛选属性值
  RxString selectedAttr = ''.obs;

  // 购物车选中的数量
  RxInt selectNum = 1.obs;

  // 顶部Tab中间文字
  List subTabList = [
    {"id": 1, "title": "商品介绍"},
    {"id": 2, "title": "规格参数"},
  ];
  RxInt subSelectIndex = 1.obs;

  @override
  void onInit() {
    super.onInit();
    scrollerControllerListener();
    getContentData();
  }

  @override
  void onClose() {
    super.onClose();
  }

  void scrollerControllerListener() {
    scrollController.addListener(() {
      // 获取渲染后元素的位置（只获取一次）
      if (gk2Position == 0 && gk3Position == 0) {
        getContainerPosition(scrollController.position.pixels);
      }
      // 优化子Tab显示逻辑 - 只有在详情区域且未进入推荐区域时才显示
      bool shouldShow =
          scrollController.position.pixels >= gk2Position &&
          scrollController.position.pixels < gk3Position;

      if (shouldShow != showSubHeaderTabs.value) {
        showSubHeaderTabs.value = shouldShow;
      }
      // 根据滚动位置自动切换选中的tab
      if (scrollController.position.pixels < gk2Position) {
        // 商品区域
        if (selectIndex.value != 1) {
          selectIndex.value = 1;
        }
      } else if (scrollController.position.pixels < gk3Position) {
        // 详情区域
        if (selectIndex.value != 2) {
          selectIndex.value = 2;
        }
      } else {
        // 推荐区域
        if (selectIndex.value != 3) {
          selectIndex.value = 3;
        }
      }
      // 显示隐藏顶部tab切换
      if (scrollController.position.pixels <= 100) {
        opacity.value = scrollController.position.pixels / 100;
        if (opacity.value > 0.96) {
          opacity.value = 1;
        }
        if (showTabs.value == true) {
          showTabs.value = false;
        }
        update();
      } else {
        if (showTabs.value == false) {
          showTabs.value = true;
          update();
        }
      }
    });
  }

  //   切换tab
  changeSelectTabIndex(index) {
    selectIndex.value = index;
    update();
  }

  //获取详情数据
  void getContentData() async {
    var response = await httpsClient.get(
      '/api/pcontent?id=${Get.arguments['id']}',
    );
    if (response != null) {
      print('商品详情的数据${response.data}');
      var tempData = PContentModel.fromJson(response.data);
      pcontent.value = tempData.result!;
      pcontentAttr.value = pcontent.value.attr!;
      //初始化Attr
      initAttr(pcontentAttr);
      // 获取商品属性
      getSelectedAttr();
      update();
    }
  }

  initAttr(List<PContentAttrModel> attr) {
    for (var i = 0; i < attr.length; i++) {
      for (var j = 0; j < attr[i].list!.length; j++) {
        if (j == 0) {
          attr[i].attrList!.add({"title": attr[i].list![j], "checked": true});
        } else {
          attr[i].attrList!.add({"title": attr[i].list![j], "checked": false});
        }
      }
    }
  }

  // 改变attr Cate 颜色 title ，玫瑰红
  changeAttr(cate, title) {
    for (var i = 0; i < pcontentAttr.length; i++) {
      if (pcontentAttr[i].cate == cate) {
        for (var j = 0; j < pcontentAttr[i].attrList!.length; j++) {
          pcontentAttr[i].attrList![j]['checked'] = false;
          if (pcontentAttr[i].attrList![j]['title'] == title) {
            pcontentAttr[i].attrList![j]['checked'] = true;
          }
        }
      }
    }
    update();
  }

  //   获取详情Tabs元素的位置
  void getContainerPosition(pixels) {
    if (_hasCalculatedPositions) return;
    try {
      // 计算第二个Tab位置
      if (gb2.currentContext != null) {
        RenderBox box2 = gb2.currentContext!.findRenderObject() as RenderBox;
        gk2Position =
            box2.localToGlobal(Offset.zero).dy +
            pixels -
            (ScreenAdapter.getStatusBarHeight() + ScreenAdapter.height(140));
      }

      // 计算第三个Tab位置
      if (gb3.currentContext != null) {
        RenderBox box3 = gb3.currentContext!.findRenderObject() as RenderBox;
        gk3Position =
            box3.localToGlobal(Offset.zero).dy +
            pixels -
            (ScreenAdapter.getStatusBarHeight() + ScreenAdapter.height(140));
      }

      // 确保gk3Position大于gk2Position
      if (gk3Position <= gk2Position) {
        gk3Position = gk2Position + 2000; // 给一个合理的差值
      }

      _hasCalculatedPositions = true;
    } catch (e) {
      print("计算位置错误: $e");
    }
  }

  //   获取Attr属性
  getSelectedAttr() {
    List tempList = [];
    for (var i = 0; i < pcontentAttr.length; i++) {
      for (var j = 0; j < pcontentAttr[i].attrList!.length; j++) {
        if (pcontentAttr[i].attrList![j]['checked']) {
          tempList.add(pcontentAttr[i].attrList![j]['title']);
        }
      }
    }
    selectedAttr.value = tempList.join(',');
  }

  //   购物车数据增加
  incCount() {
    selectNum.value++;
    update();
  }

  //   购物车数据减少
  decCount() {
    if (selectNum > 1) {
      selectNum.value--;
      update();
    }
  }

  // 加入购物车

  void addCart() {
    print('加入购物车');
    getSelectedAttr();
    CartServices.addCart(pcontent.value, selectedAttr.value, selectNum.value);
    Get.back();
    Get.snackbar('提示', '加入购物车成功');
  }

  // 立即购买
  void buy() {
    getSelectedAttr();
    Get.back();
    print('立即购买');
  }
}
